package com.abcode.test.oracletest.query.define.commonquery;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CommonQueryServiceImpl implements CommonQueryService {
     @Autowired
    private SqlSessionFactory sqlSessionFactory;
     @Override
    public List<Map<String, Object>> query(String tableName, List<String> queryFields, List<QueryCondition> queryConditions,
                                           int pageNum, int pageSize, String orderByField, boolean isAsc) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(queryFields.toArray(new String[0]))
                    .eq("1", 1); // 添加一个无意义的条件，避免后面的条件为空时报错
            for (QueryCondition queryCondition : queryConditions) {
                String fieldName = queryCondition.getFieldName();
                Object fieldValue = queryCondition.getFieldValue();
                String operator = queryCondition.getOperator();
                switch (operator) {
                    case "=":
                        queryWrapper.eq(fieldName, fieldValue);
                        break;
                    case ">":
                        queryWrapper.gt(fieldName, fieldValue);
                        break;
                    case ">=":
                        queryWrapper.ge(fieldName, fieldValue);
                        break;
                    case "<":
                        queryWrapper.lt(fieldName, fieldValue);
                        break;
                    case "<=":
                        queryWrapper.le(fieldName, fieldValue);
                        break;
                    case "!=":
                        queryWrapper.ne(fieldName, fieldValue);
                        break;
                    case "like":
                        queryWrapper.like(fieldName, fieldValue);
                        break;
                    default:
                        throw new IllegalArgumentException("Invalid operator: " + operator);
                }
            }
            if (StringUtils.isNotBlank(orderByField)) {
                queryWrapper.orderBy(true,isAsc, orderByField);
            }
            PageHelper.startPage(pageNum, pageSize);
           // List<Map<String, Object>> data = sqlSession.selectList(new LambdaQueryWrapper<Map<String, Object>>());
            return null;
        } finally {
            sqlSession.close();
        }
    }


}